package controllers

import (
	"fmt"
	"go-web/db"
	"go-web/models"

	"github.com/astaxie/beego"
)

type DetailController struct {
	beego.Controller
}

func (c *DetailController) Get() {
	id, _ := c.GetInt(":id")
	if id <= 0 {
		c.Redirect("/", 302)
		return
	}
	detail := &models.Detail{Id: id}
	ok, _ := db.Mysql.Get(detail)
	if !ok {
		c.Redirect("/", 302)
		return
	}
	detail.Hits += 1
	db.Mysql.Id(id).Cols("hits").Update(detail)
	prevDetail := make([]models.Detail, 0)
	db.Mysql.Where("Bigclassid=? And SmallClassId=? And id<?", detail.Bigclassid, detail.Smallclassid, detail.Id).Desc("updatetime").Limit(1).Select("id,title,updatetime").Find(&prevDetail)
	if len(prevDetail) > 0 {
		c.Data["Prev"] = fmt.Sprintf(`<li>
                            <a href="/detail/%d">上一篇：%s</a>
                            <span style="float:right;">%s</span>
                        </li>`, prevDetail[0].Id, prevDetail[0].Title, prevDetail[0].Updatetime.Format("2006-01-02"))
	} else {
		c.Data["Prev"] = `<li><a >上一篇：已经是第一条了</a></li>`
	}
	nextDetail := make([]models.Detail, 0)
	db.Mysql.Where("Bigclassid=? And SmallClassId=? And id > ?", detail.Bigclassid, detail.Smallclassid, detail.Id).Desc("updatetime").Limit(1).Select("id,title,updatetime").Find(&nextDetail)
	if len(nextDetail) > 0 {
		c.Data["Next"] = fmt.Sprintf(`<li>
                            <a href="/detail/%d">下一篇：%s</a>
                            <span style="float:right;">%s</span>
                        </li>`, nextDetail[0].Id, nextDetail[0].Title, nextDetail[0].Updatetime.Format("2006-01-02"))
	} else {
		c.Data["Next"] = `<li><a >下一篇：已经是最后一条了</a></li>`
	}
	data := make([]models.Detail, 0)
	db.Mysql.Where("Bigclassid=? And SmallClassId=?", detail.Bigclassid, detail.Smallclassid).Desc("updatetime").Limit(6, 0).Select("id,title,updatetime").Find(&data)
	c.Data["NewList"] = data
	SetBigClassActive(detail.Bigclassid)
	c.Data["Data"] = detail
	c.Data["Navigation"] = NavigationBar
	c.TplName = "detail.html"
}
